Import mojo
Import timelinefx

Class checkCollisionExample Extends App

	Field poly:tlPolygon
	
	'create a box to move about
	Field box:tlBox
	
	'a local collision result to store the result of the collision test
	Field result:tlCollisionResult = New tlCollisionResult
	
	'some velocity vectors to move the box about
	Field VelVector:tlVector2 = New tlVector2(0, 0)
	Field VelMatrix:tlMatrix2 = New tlMatrix2
	Field Direction:Float
	Field speed:Float = 4

	Method OnCreate()
		box = new tlBox(400, 300, 100, 100)
		Local verts:Float[] =[0.0, 0.0, -150.0, 100.0, 50.0, 150.0, 185.0, 100.0, 300.0, 0.0]
		poly = CreatePolygon(400, 200, verts)
		box = CreateBox(100, 100, 20, 20)
		
		SetUpdateRate 60
	End
	
	Method OnUpdate()
		'rotate the polygon by 1 degree every frame
		poly.Rotate(1)
	
		'some basic movement controls for the box
		If KeyDown(KEY_UP) Direction = 0
		If KeyDown(KEY_RIGHT) Direction = 90
		If KeyDown(KEY_DOWN) Direction = 180
		If KeyDown(KEY_LEFT) Direction = 270
		If KeyDown(KEY_RIGHT) And KeyDown(KEY_DOWN) Direction = 135
		If KeyDown(KEY_DOWN) And KeyDown(KEY_LEFT) Direction = 225
		If KeyDown(KEY_UP) And KeyDown(KEY_RIGHT) Direction = 45
		If KeyDown(KEY_LEFT) And KeyDown(KEY_UP) Direction = 315
		If KeyDown(KEY_UP) Or KeyDown(KEY_DOWN) Or KeyDown(KEY_LEFT) Or KeyDown(KEY_RIGHT)
			VelVector.SetPosition(0, -speed)
		Else
			VelVector.SetPosition(0, 0)
		End If
		VelMatrix.Set(Cos(Direction), Sin(Direction), -Sin(Direction), Cos(Direction))
		VelVector = VelMatrix.TransformVector(VelVector).Unit()
		'set the box velocity so that the collision check can see whether the 2 objects will collide
		'the next frame. You don't *have* to do this, but it makes for more accurate collisions
		box.SetVelocityVector(VelVector.Scale(speed))

		'check for a collision with the poly
		result = CheckCollision(box, poly)
		
		'prevent the box from overlapping the poly
		PreventOverlap(result)
		
		'move the box. Important to do this after the collision check, but only if you're setting
		'the box velicity.
		box.UpdatePosition()
	End
	
	Method OnRender()
		Cls
		box.Draw()
		poly.Draw()
	End
End

Function Main()
	New checkCollisionExample
	
End

